package com.maxsalad.uc.service;

import com.maxsalad.uc.dao.DishDao;
import com.maxsalad.uc.dao.OrderDetailDao;
import com.maxsalad.uc.dto.DOrderDetailDto;
import com.maxsalad.uc.pojo.TDishEntity;
import com.maxsalad.uc.pojo.TOrderDetailEntity;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Created by 2014-400 on 2016-03-17.
 */
@Service
public class OrderDetailService extends BaseService {
    private static final Logger log = LoggerFactory.getLogger(OrderDetailService.class);

    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private DishDao dishDao;

    public Map queryOrderDetailByOrderId(long orderId) throws Exception {
        TOrderDetailEntity orderDetailEntity = new TOrderDetailEntity();
        orderDetailEntity.setOrderId(orderId);
        Map map = orderDetailDao.queryAllOrderDetail(orderDetailEntity);
        List<TOrderDetailEntity> list = (List<TOrderDetailEntity>) map.get("rows");
        if (CollectionUtils.isNotEmpty(list)) {
            Long[] ids = new Long[list.size()];
            int i = 0;
            for (TOrderDetailEntity entity : list) {
                ids[i] = entity.getDishId();
                i++;
            }
            List<TDishEntity> listDish = dishDao.queryDishByIds(ids);

            List<DOrderDetailDto> temp = new ArrayList<DOrderDetailDto>();
            DOrderDetailDto dto = null;
            for (TOrderDetailEntity entity : list) {
                dto = new DOrderDetailDto();
                BeanUtils.copyProperties(dto, entity);
                Optional<TDishEntity> optional = listDish.stream().filter(t -> t.getId() == entity.getDishId()).findFirst();
                if (optional.isPresent()) {
                    TDishEntity dishEntity = optional.get();
                    dto.setBarcode(dishEntity.getBarcode());
                    dto.setDishName(dishEntity.getDishName());
                    dto.setDishOrder(dishEntity.getDishOrder());
                }
                temp.add(dto);
            }

            map.put("rows", temp);
        }
        return map;
    }
}